<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Model\Logic;

use ReflectionException;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Consul\Agent;
use Swoft\Consul\Catalog;
use Swoft\Consul\Exception\ClientException;
use Swoft\Consul\Exception\ServerException;
use Swoft\Consul\Health;
use Swoft\Consul\KV;
use Swoft\Consul\Session;
use Swoft\Log\Helper\CLog;
use Swoft\Stdlib\Helper\JsonHelper;

/**
 * Class ConsulLogic
 *
 * @since 2.0
 *
 * @Bean("ConsulLogic")
 */
class ConsulLogic
{
    /**
     * @Inject()
     *
     * @var Agent
     */
    private $agent;

    /**
     * @Inject()
     *
     * @var Health
     */
    private $health;

    /**
     * @Inject()
     *
     * @var Catalog
     */
    private $catalog;

    /**
     * @Inject()
     *
     * @var KV
     */
    private $kv;

    /**
     * @Inject()
     *
     * @var Session
     */
    private $session;

    /**
     * @throws ReflectionException
     * @throws ContainerException
     * @throws ClientException
     * @throws ServerException
     */
    public function kv(): void
    {
        $value = 'value content';
        $this->kv->put('/test/my/key', $value);

        $response = $this->kv->get('/test/my/key');
        var_dump($response->getBody(), $response->getResult());
    }

    /**
     * 根据服务名称获取微服务注册信息
     * @param string $serviceName 服务名称
     * @return array
     * @throws ClientException
     * @throws ServerException
     */
    public function getServiceList(string $serviceName): array
    {
        $arrJson = JsonHelper::decode($this->agent->services()->getBody(), true);
        $arrCheck = JsonHelper::decode($this->agent->checks()->getBody() , true );
        //TODO:兼容同一个服务多部署
        if (false){
            $list = [];
            foreach ( $arrJson as $serv) {
                if ($serv ['Service'] == $serviceName){
                    $list [] = $serv;
                }
            }

            if (empty($list))
            {
                return [];
            }
            //随机命中一个服务
            $idx = mt_rand(0 , count($list)) ;
            return $list [$idx];
        }else
        {
            //是否通过服务
            if (!isset($arrJson[$serviceName])) {
                return [];
            }

//            //服务校验是否通过
            if (!isset($arrCheck [ 'service:'.$serviceName]) || $arrCheck [ 'service:'.$serviceName] ['Status'] != 'passing') {
                return [];
            }
            return $arrJson[$serviceName];
        }

    }
}
